package Solutions;

import java.util.Stack;

/**
 * @Classname RemoveKdigits
 * @Description TODO
 * @Date 2021/3/6 20:38
 * @Created by ASUS
 */
public class RemoveKdigits {
    public String removeKdigits(String num, int k) {

        Stack<Integer> stack = new Stack<>();

        char[] chars = num.toCharArray();
        for (char aChar : chars) {
            int value = aChar - '0';
            while (!stack.isEmpty() && value < stack.peek() && k > 0){
                stack.pop();
                k--;
            }
            stack.push(value);

        }
        while (k-- > 0) {
            stack.pop();
        }

        StringBuilder sb = new StringBuilder();
        for (Integer integer : stack) {
            if(integer == 0){
                continue;
            }
            sb.append(integer);
        }

        return sb.toString();
    }
}
